//
//  InsertViewController.m
//  primoPrj
//
//  Created by Giuseppe on 15/11/13.
//
//

#import "InsertViewController.h"
#import "Element.h"


@interface InsertViewController ()

@end


@implementation InsertViewController


@synthesize delegate = _delegate;
@synthesize eventStore = _eventStore;


#pragma mark - -- Inizializzazione --

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        // Custom initialization
        
        self.view.backgroundColor = [UIColor whiteColor];
        
        [self createControls:true];
        
        _element= [[Element alloc]
                            initWithName:@"x"
                            ID:0
                            Origin:@"x"
                            Description:@"x"
                            Image:@"x"
                            Telefono:@"x"
                            Date:@"x"];
        
    }
    return self;
}


- (id)initWithElement:(Element *)element {

    self.view.backgroundColor = [UIColor whiteColor];
    
    _element = element;
    
    [self createControls: false];
    
    txtNome.text = element.name;
    txtDescrizione.text = element.description;
    txtOrigine.text=element.origin;
    txtAllarme.text=element.date;
    
    // new -->
    AppDelegate * AppDel = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    imgView.image = [AppDel loadImage: _element.img];
    
    return self;
}


-(void) createControls:(BOOL) bar {
    
    // new -->
    int offset = 40;

    UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 20, 320, 45)];
    UINavigationItem *navItem = [UINavigationItem alloc];
    //navItem.title = @"Nuovo elemento";
    
    [navbar pushNavigationItem:navItem animated:false];
    [self.view addSubview:navbar];

    NSLog(@"offset: %d",offset);

    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 160, 140)];
    imgView.image = [UIImage imageNamed:@"rubrica"];
    
    UILabel *nome = [[UILabel alloc]initWithFrame:CGRectMake(10, 160+offset, 300, 20)];
    [nome setText:@"Nome"];
    [nome setTextColor:[UIColor grayColor]];
    [nome setFont:[UIFont boldSystemFontOfSize:16]];
    
    UILabel *descrizione = [[UILabel alloc]initWithFrame:CGRectMake(170, 160+offset, 300, 20)];
    [descrizione setText:@"Cognome"];
    [descrizione setTextColor:[UIColor grayColor]];
    [descrizione setFont:[UIFont boldSystemFontOfSize:16]];
    
    UILabel *origine = [[UILabel alloc]initWithFrame:CGRectMake(10, 220+offset, 300, 20)];
    [origine setText: @"Indirizzo"];
    [origine setTextColor:[UIColor grayColor]];
    [origine setFont:[UIFont boldSystemFontOfSize:16]];
    
    UILabel *allarme = [[UILabel alloc]initWithFrame:CGRectMake(10, 280+offset, 300, 20)];
    [allarme setText: @"Allarme"];
    [allarme setTextColor:[UIColor grayColor]];
    [allarme setFont:[UIFont boldSystemFontOfSize:16]];
    
    txtNome = [[UITextField alloc]initWithFrame:CGRectMake(10, 180+offset, 140, 40)];
    [txtNome setPlaceholder:@"inserisci il nome"];
    [txtNome setBackgroundColor:[UIColor whiteColor]];
    [txtNome setBorderStyle:UITextBorderStyleRoundedRect];
    [txtNome setClearButtonMode:UITextFieldViewModeWhileEditing];
    [txtNome setDelegate:self];
    
    txtDescrizione = [[UITextField alloc]initWithFrame:CGRectMake(170, 180+offset, 140, 40)];
    [txtDescrizione setPlaceholder:@"inserisci il cognome"];
    [txtDescrizione setBackgroundColor:[UIColor whiteColor]];
    [txtDescrizione setBorderStyle:UITextBorderStyleRoundedRect];
    [txtDescrizione setClearButtonMode:UITextFieldViewModeWhileEditing];
    [txtDescrizione setDelegate:self];
    
    txtOrigine = [[UITextField alloc]initWithFrame:CGRectMake(10, 240+offset, 300, 40)];
    [txtOrigine setPlaceholder:@"inserisci l'indirizzo"];
    [txtOrigine setBackgroundColor:[UIColor whiteColor]];
    [txtOrigine setBorderStyle:UITextBorderStyleRoundedRect];
    [txtOrigine setClearButtonMode:UITextFieldViewModeWhileEditing];
    [txtOrigine setDelegate:self];
    
    txtAllarme = [[UITextField alloc]initWithFrame:CGRectMake(10, 300+offset, 300, 40)];
    [txtAllarme setPlaceholder:@"inserisci la data"];
    [txtAllarme setBackgroundColor:[UIColor whiteColor]];
    [txtAllarme setBorderStyle:UITextBorderStyleRoundedRect];
    [txtAllarme setClearButtonMode:UITextFieldViewModeWhileEditing];
    [txtAllarme setDelegate:self];
    
    //photoButton = [[UIButton alloc]initWithFrame:CGRectMake(220,30,80,40)];
    photoButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 50+offset, 100, 100)];
    //[photoButton setTitle:@"Foto" forState:UIControlStateNormal];
    [photoButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [photoButton.layer setBorderWidth:1.0f];
    [photoButton.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
    // new --->
    [photoButton setBackgroundImage:[UIImage imageNamed:@"rubrica"] forState:UIControlStateNormal];
    [photoButton addTarget:self
                    action:@selector(browseImage)
          forControlEvents:UIControlEventTouchUpInside];
    
    alarmButton = [[UIButton alloc]initWithFrame:CGRectMake(220,80+offset,80,40)];
    [alarmButton setTitle:@"Allarme" forState:UIControlStateNormal];
    [alarmButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [alarmButton.layer setBorderWidth:1.0f];
    [alarmButton.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [alarmButton addTarget:self
                    action:@selector(showDateAlarm)
          forControlEvents:UIControlEventTouchUpInside];
    
    clearButton = [[UIButton alloc]initWithFrame:CGRectMake(80,360+offset,80,30)];
    [clearButton setTitle:@"CLEAR" forState:UIControlStateNormal];
    [clearButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [clearButton.layer setBorderWidth:1.0f];
    [clearButton.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [clearButton addTarget:self
                    action:@selector(clearBtnPressed)
          forControlEvents:UIControlEventTouchUpInside];
    
    saveButton = [[UIButton alloc]initWithFrame:CGRectMake(180,360+offset,80,30)];
    [saveButton setTitle:@"SAVE" forState:UIControlStateNormal];
    [saveButton.layer setBorderWidth:1.0f];
    [saveButton.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [saveButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [saveButton addTarget:self
                   action:@selector(saveBtnPressed)
         forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:photoButton];
    [self.view addSubview:alarmButton];
    [self.view addSubview:saveButton];
    [self.view addSubview:clearButton];
    [self.view addSubview:txtOrigine];
    [self.view addSubview:txtNome];
    [self.view addSubview:txtDescrizione];
    [self.view addSubview:txtAllarme];
    //[self.view addSubview:imgView];
    [self.view addSubview:nome];
    [self.view addSubview:descrizione];
    [self.view addSubview:origine];
    [self.view addSubview:allarme];

}


- (void)viewDidLoad
{
    [super viewDidLoad];

	// Do any additional setup after loading the view.
}


#pragma mark - -- Riposizionamento UITextfields --



- (BOOL)textFieldShouldReturn: (UITextField *)textField
{
    if (textField == txtNome ) {
        [textField resignFirstResponder];
        [txtDescrizione becomeFirstResponder];
    } else if (textField == txtDescrizione) {
        [txtDescrizione resignFirstResponder];
        [txtOrigine becomeFirstResponder];
    } else if (textField == txtOrigine) {
        [txtOrigine resignFirstResponder];
        [txtAllarme becomeFirstResponder];
    } else if (textField == txtAllarme) {
        [txtAllarme resignFirstResponder];
    }
    
    return YES;
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{

    float distance=0;
    
    if(textField==txtNome || textField==txtDescrizione ){
        distance = -100;
    } else if (textField==txtOrigine){
        distance = -150;
    } else if (textField==txtAllarme){
        distance = -200;
    }
    
    CGAffineTransform translateUp = CGAffineTransformMakeTranslation(0.0, distance);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    self.view.transform = translateUp;
    [UIView commitAnimations];
    return YES;
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    
     if(textField==txtAllarme){
        CGAffineTransform translateUp = CGAffineTransformMakeTranslation(0.0, 0.0);
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.2];
        self.view.transform = translateUp;
        [UIView commitAnimations];
    }
    return YES;
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"touchesBegan");
    [txtNome endEditing:YES];
    [txtOrigine endEditing:YES];
    [txtDescrizione endEditing:YES];
    [txtAllarme endEditing:YES];
}


#pragma mark - -- Buttons --

-(void) saveBtnPressed
{
    
    ListViewController *listViewController = [[ListViewController alloc]initWithNibName:nil bundle:nil];
    self.delegate = listViewController;
    
    NSLog(@"delegato:   : %@", self.delegate);
    
    if ( [txtNome.text isEqual: @""] || [txtOrigine.text  isEqual: @""] || [txtDescrizione.text  isEqual: @""]) {
        
        UIAlertView * alertView =
            [[UIAlertView alloc]initWithTitle:@"Attenzione!"
                                      message:@"Tutti i campi sono obbligatori"
                                     delegate:nil
                            cancelButtonTitle:nil
                            otherButtonTitles:@"Ok", nil];
        [alertView show];
        return;
    }
    

    
    int randomValue = arc4random() % 999999;
    elemImage = [NSString stringWithFormat:@"%d",randomValue];
    
    // new -->
    AppDelegate* AppDel = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    [AppDel saveImage: imgView.image WithName:elemImage];
    //[self saveImage: imgView.image WithName:elemImage];

    
    _element.name = txtNome.text;
    _element.origin = txtOrigine.text;
    _element.description = txtDescrizione.text;
    _element.tel = @"555-000";
    _element.img = elemImage;
    
    /*
     Element * element= [[Element alloc]
     initWithName:txtNome.text
     ID:0
     Origin:txtOrigine.text
     Description:txtDescrizione.text
     Image:elemImage
     Telefono:@"x"
     Date:@"x"];
     */
    
    [self setReminder];
    
    [self.delegate insertNewElement:_element];
    
    [self clearBtnPressed];
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
     NSLog(@"Save button Pressed");
}


-(void) clearBtnPressed
{
    [txtNome setText:@""];
    [txtOrigine setText:@""];
    [txtDescrizione setText:@""];
    [txtAllarme setText:@""];
    NSLog(@"Clear button Pressed");
}


- (BOOL) browseImage {
    

    UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
    mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    
    mediaUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeSavedPhotosAlbum];
    
    mediaUI.allowsEditing = YES;
    
    mediaUI.delegate = self;
    
    [self presentViewController:mediaUI animated:YES completion:nil];
    
    return YES;
}


-(void) showDateAlarm {

    DateViewController *dateViewController = [[DateViewController alloc] initWithElement:_element];
    [self presentViewController:dateViewController animated:YES completion:nil];

}

#pragma mark - -- Image picker --

- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToUse;
    
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
        
        editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
        
        if (editedImage) {
            imageToUse = editedImage;
        } else {
            imageToUse = originalImage;
        }

        imgView.image=imageToUse;
        [photoButton setBackgroundImage:imageToUse forState:UIControlStateNormal];
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];

}


-(void )setReminder {
    
    if ([_element.date length]>1) {
        
        _eventStore = [[EKEventStore alloc]init];
        
        if ([_eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]){
            [_eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
            {


             
                 NSLog(@"GRANTED: %c", granted);
                 for (EKSource *source in _eventStore.sources)
                 {
                     if (source.sourceType == EKSourceTypeCalDAV || source.sourceType == EKSourceTypeLocal)
                     {
                         NSLog(@"I found it");
                         break;
                     }
                 }
             }];
            
        }
        
    }
        
        /*if (_eventStore == nil)
        {
            
            
            [_eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {
                
                if (!granted) NSLog(@"Access to store not granted");
            }];
        }
        
        if (_eventStore != nil) [self createReminder];
    }*/
}


-(void)createReminder
{
    EKReminder *reminder = [EKReminder reminderWithEventStore:self.eventStore];
    reminder.title = _element.name;
    reminder.calendar = [_eventStore defaultCalendarForNewEvents];
        
    //--- NSString to NSDAte
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"dd-MM-yyyy"];
    NSDate *date = [df dateFromString: _element.date];
    
    NSLog(@"in createReminder - element.date: %@",_element.date);
    NSLog(@"in createReminder - date: %@",date);
    
    EKAlarm *alarm = [EKAlarm alarmWithAbsoluteDate:date];
    [reminder addAlarm:alarm];
    NSError *error = nil;
    [_eventStore saveReminder:reminder commit:YES error:&error];
    
    if (error)
        NSLog(@"error = %@", error);
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
